package cn.outsourcing.supermarket.common.utils;

import cn.outsourcing.supermarket.common.PageResult;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 分页数据构造工具
 *
 * @author gzkemays
 * @since 2021/10/21 22:17
 */
public class PageResultUtils<T> {
  public static <T> PageResult<T> parseListPageObjs(IPageUtils<?> pages, List<T> list) {
    long size = pages.getSize();
    long total = pages.getTotal();
    BigDecimal decimal = BigDecimal.valueOf(Math.ceil((double) total / size));
    return PageResult.<T>builder()
        .pageSize(pages.getSize())
        .currentPage(pages.getCurrent())
        .totalPages(decimal.intValue())
        .count((int) total)
        .data(list)
        .build();
  }

  public static <T> PageResult<T> parseSetPageObjs(IPageUtils<?> pages, Set<T> list) {
    long size = pages.getSize();
    long total = pages.getTotal();
    BigDecimal decimal = BigDecimal.valueOf(Math.ceil((double) total / size));
    return PageResult.<T>builder()
        .pageSize(pages.getSize())
        .currentPage(pages.getCurrent())
        .totalPages(decimal.intValue())
        .count((int) total)
        .data(new ArrayList<>(list))
        .build();
  }

  /**
   * 根据 IPage 返回对象
   *
   * @param page IPage 值
   * @param <T> 泛型
   * @return 分页结果
   */
  public static <T> PageResult<T> parseListPageI(IPage<T> page) {
    long size = page.getSize();
    long total = page.getTotal();
    BigDecimal decimal = BigDecimal.valueOf(Math.ceil((double) total / size));
    return PageResult.<T>builder()
        .pageSize(page.getSize())
        .currentPage(page.getCurrent())
        .totalPages(decimal.intValue())
        .count((int) total)
        .data(page.getRecords())
        .build();
  }

  public static <T> PageResult<T> emptyData() {
    return PageResult.<T>builder()
        .count(0)
        .totalPages(0)
        .pageSize(0)
        .currentPage(0)
        .data(new ArrayList<>())
        .build();
  }
}
